package br.edu.ufcg.embedded.eolica.facade;

import java.util.Vector;

import br.edu.ufcg.embedded.eolica.domain.Attribute;
import br.edu.ufcg.embedded.eolica.domain.Station;
import br.edu.ufcg.embedded.eolica.domain.User;
import br.edu.ufcg.embedded.eolica.exception.FacadeException;
import br.edu.ufcg.embedded.eolica.exception.PersistenceException;
import br.edu.ufcg.embedded.eolica.persistence.Rms;

public class Facade {
	private static Facade instance;
	private Rms userPersistence;
	private Rms attributePersistence;
	private User user;
	
	private Facade() {
		userPersistence = new Rms(Rms.USER_RECORD);
		attributePersistence = new Rms(Rms.ATTRIBUTE_RECORD);
	}
	
	public static Facade getInstance() {
		if (instance == null)
			instance = new Facade();
		
		return instance;
	}
	
	public void saveUser(User user) throws FacadeException {
		try {
			if (this.user != null) {
				userPersistence.update(user);
				this.user = user;
			} else {
				userPersistence.save(user);
				this.user = user;
			}			
		} catch (PersistenceException e) {
			throw new FacadeException();
		}
	}
	
	public User getUser() throws FacadeException {
		try {
			if (user == null) {
				Vector v = userPersistence.readAll();
				if(v.size() != 0)
					user = (User) v.elementAt(0);
			}
		} catch (PersistenceException e) {
			throw new FacadeException();
		}
		
		return user;
	}
		
	public void deleteUser() throws FacadeException {
		try {
			userPersistence.deleteAll();
			user = null;
		} catch (PersistenceException e) {
			throw new FacadeException();
		}
	}
}
